<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div><input type="text" id="input" /> <button id="send">发送</button></div>
    <div class="list"></div>
    <iframe src="./ChannelMessagingAPIChild.html" frameborder="0"></iframe>
    <script>
      const channel = new MessageChannel();
      const list = document.querySelector('.list');
      const iframe = document.querySelector('iframe');
      // 等待 iframe 加载
      iframe.addEventListener('load', onLoad, { once: true });
      function onLoad() {
        // 发送端口给 iframe
        channel.port1.onmessage = (e) => {
          list.innerHTML += `<p>${e.data}</p>`;
        };

        iframe.contentWindow.postMessage('open port', '*', [channel.port2]);
      }

      document.querySelector('#send').addEventListener('click', () => {
        const input = document.querySelector('#input');
        const message = input.value;
        channel.port1.postMessage(message);
      });
    </script>
  </body>
</html>
